package com.ztgf.shopping.service.shop;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ztgf.commodity.models.dto.CommodityInfoDTO;
import com.ztgf.commodity.models.service.ICommodityInfoService;
import com.ztgf.commodity.models.service.ICommoditySpecificationRelationService;
import com.ztgf.commodity.models.vo.CommodityAttrPriceVO;
import com.ztgf.common.constant.CommonParameter;
import com.ztgf.common.constant.Result;
import com.ztgf.common.enums.CodeEnum;
import com.ztgf.dubbo.exception.ServiceException;
import com.ztgf.common.utils.StrUtils;
import com.ztgf.db.utils.RedisUtil;
import com.ztgf.order.models.dto.OrderCommodityRelationDTO;
import com.ztgf.order.models.dto.OrderInfoDTO;
import com.ztgf.order.models.dto.purchase.PurchaseCommodityBargainDTO;
import com.ztgf.order.models.dto.purchase.PurchaseCommodityBargainLogDTO;
import com.ztgf.order.models.dto.purchase.PurchaseCommodityDTO;
import com.ztgf.order.models.dto.purchase.PurchaseInfoDTO;
import com.ztgf.order.models.enums.BargainStateEnum;
import com.ztgf.order.models.service.IOrderCommodityRelationService;
import com.ztgf.order.models.service.IOrderInfoService;
import com.ztgf.order.models.service.async.IAsyncOrderService;
import com.ztgf.order.models.service.purchase.IPurchaseCommodityBargainLogService;
import com.ztgf.order.models.service.purchase.IPurchaseCommodityBargainService;
import com.ztgf.order.models.service.purchase.IPurchaseCommodityService;
import com.ztgf.order.models.service.purchase.IPurchaseInfoService;
import com.ztgf.order.models.vo.purchase.PurchaseCommodityVO;
import com.ztgf.shopping.common.config.YmlConfig;
import com.ztgf.shopping.mapper.shop.ShopInfoMapper;
import com.ztgf.shopping.mapper.shop.ShopShoppingCartMapper;
import com.ztgf.shopping.models.bo.shop.ShopShoppingCartBO;
import com.ztgf.shopping.models.bo.shop.ShopShoppingCartCmsBo;
import com.ztgf.shopping.models.bo.shop.ShopShoppingCartSaveBO;
import com.ztgf.shopping.models.dto.shop.ShopInfoDTO;
import com.ztgf.shopping.models.dto.shop.ShopShoppingCartDTO;
import com.ztgf.shopping.models.service.shop.IShopInfoService;
import com.ztgf.shopping.models.service.shop.IShopShoppingCartService;
import com.ztgf.shopping.models.vo.shop.*;
import com.ztgf.sys.models.dto.SysUserDTO;
import com.ztgf.sys.models.service.ISysAreaService;
import com.ztgf.user.models.dto.UserInfoDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import static com.ztgf.common.utils.UtilConstants.getIds;

/**
 * 用户购物车表控制器
 *
 * @author zhanghualang
 * @Date 2020-05-27 14:05:12
 */
@Slf4j
@DubboService
public class ShopShoppingCartServiceImpl extends ServiceImpl<ShopShoppingCartMapper, ShopShoppingCartDTO> implements IShopShoppingCartService {

    @Resource
    private YmlConfig ymlConfig;
    @DubboReference
    private ISysAreaService sysAreaService;
    @Autowired
    private RedisUtil redisUtil;
    @DubboReference
    private ICommodityInfoService iCommodityInfoService;
    @DubboReference
    private IPurchaseCommodityBargainLogService purchaseCommodityBargainLogService;
    @DubboReference
    private ICommoditySpecificationRelationService iCommoditySpecificationRelationService;
    @DubboReference
    private IPurchaseCommodityService purchaseCommodityService;
    @Autowired
    private IShopInfoService iShopInfoService;
    @DubboReference
    private IPurchaseCommodityBargainService iPurchaseCommodityBargainService;
    @DubboReference
    private IAsyncOrderService asyncOrderService;
    @DubboReference
    private IOrderInfoService iOrderInfoService;

    @DubboReference
    private IOrderCommodityRelationService iOrderCommodityRelationService;

    @DubboReference
    private IShopShoppingCartService shopShoppingCartService;

    @Autowired
    private ShopShoppingCartMapper shopShoppingCartMapper;

    @DubboReference
    private IPurchaseInfoService purchaseInfoService;

    @Override
    public boolean add(ShopShoppingCartSaveBO saveBO) {
        //商品规格属性ids
        String ids = getIds(saveBO.getSpecificationIds());
        //判断是否购物车已有
        Wrapper<ShopShoppingCartDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("shop_id", saveBO.getShopId()).eq("commodity_id", saveBO.getCommodityId()).eq("specification_ids", ids);
        ShopShoppingCartDTO shopShoppingCartDTO = this.selectOne(wrapper);
        ShopShoppingCartDTO dto = new ShopShoppingCartDTO();
        if (shopShoppingCartDTO != null) {
            //购物车已经存在
            dto.setId(shopShoppingCartDTO.getId());
            dto.setNumber(shopShoppingCartDTO.getNumber() + saveBO.getNumber());
            return this.updateById(dto);
        } else {
            BeanUtils.copyProperties(saveBO, dto);
            Long id = ymlConfig.getPkId();
            dto.setId(id);
            dto.setSpecificationIds(ids);
            return this.insert(dto);
        }
    }

    @Override
    public ShopShoppingCartVO queryShoppingCartPageList(ShopShoppingCartBO bo) {
        ShopShoppingCartVO shopShoppingCartVO = new ShopShoppingCartVO();
        ArrayList<ShopCommodityCartVO> shopCommodityCartVOLoseArrayList = new ArrayList<ShopCommodityCartVO>();//失效商品

        ArrayList<ShopCommodityVO> shopPurchaseCommodityCartVOList = new ArrayList<ShopCommodityVO>();

        //根据购物车商品的属性，以购物车所属店铺分组。得到所属店铺ID，商品ids 组成的集合
        List<ShopShoppingVO> shopShoppingVOList = baseMapper.queryGroupByShopId(bo.getShopId());
        ArrayList<ShopCommodityVO> shopCommodityVOS = new ArrayList<ShopCommodityVO>();
        //获取购物车普通商品信息
        for (ShopShoppingVO shopShoppingVO : shopShoppingVOList) {
            ShopCommodityVO shopCommodityVO = new ShopCommodityVO();
            shopCommodityVO.setShopId(shopShoppingVO.getCommodityShopId());//加入该分组的商品所属店铺ID
            ShopInfoDTO shopInfoDTO = iShopInfoService.selectById(shopShoppingVO.getCommodityShopId());
            shopCommodityVO.setName(shopInfoDTO.getShopName());//加入该分组的商品所属店铺名称
            shopCommodityVO.setShopPayType(shopInfoDTO.getShopPayType());//设置店铺支付类型
            //初始化商品和价格信息和价格对比vo
            ArrayList<ShopCommodityCartVO> shopCommodityCartVOS = new ArrayList<ShopCommodityCartVO>();
            //获取所有该所属店铺下的所有商品
            if(null != shopShoppingVO.getCommodityIds()) {
                List<CommodityInfoDTO> commodityInfoDTOList = iCommodityInfoService.queryByIds(shopShoppingVO.getCommodityIds());
                for (CommodityInfoDTO commodityInfoDTO : commodityInfoDTOList) {
                    //获取购物车同种商品不通规格列表
                    Wrapper<ShopShoppingCartDTO> wrapper = new EntityWrapper<>();
                    wrapper.eq("shop_id", bo.getShopId()).eq("commodity_id", commodityInfoDTO.getId());
                    List<ShopShoppingCartDTO> shopShoppingCartDTOList = this.selectList(wrapper);

                    for (ShopShoppingCartDTO cartDTO : shopShoppingCartDTOList) {
                        ShopCommodityCartVO shopCommodityCartVO = new ShopCommodityCartVO();

                        //根据商品ID和规格属性IDS  查出相关属性价格 所需参数店铺ID 。规格属性IDS。规格属性IDs 需要通过购物车查
                        Long commodityId = commodityInfoDTO.getId();
                        String specification_ids = cartDTO.getSpecificationIds();
                        //判断购物车商品是否为询盘
                        if (null == cartDTO.getType() || cartDTO.getType() != 1) {
                            CommodityAttrPriceVO commodityAttrPriceVO = iCommodityInfoService.getShoppingCartGoods(commodityId, specification_ids);
                            if (commodityAttrPriceVO.getId() == null) {
                                continue;
                            }
                            shopCommodityCartVO.setCommodityAttrPriceVO(commodityAttrPriceVO);//将规格价格信息加入

                            //或库存为0
                            if (commodityAttrPriceVO.getInventoryNumber() <= 0) {
                                shopCommodityCartVO.setFailType(1);//失效原因 0下架。1库存没有
                                shopCommodityCartVOLoseArrayList.add(shopCommodityCartVO);
                                continue;
                            }

                            //价格对比
                            if (commodityAttrPriceVO.getPrice().compareTo(cartDTO.getPrice()) < 0) {
                                //此时价格小于加入购入车价格
                                shopCommodityCartVO.setLower(1);//价格是否降低 0正常，1降低
                            } else {
                                shopCommodityCartVO.setLower(0);//价格是否降低 0正常，1降低
                            }

                            //判断商品是否下架
                            if (commodityInfoDTO.getIsPublish() == 0) {
                                shopCommodityCartVO.setFailType(0);//失效原因 0下架。1库存没有
                                shopCommodityCartVOLoseArrayList.add(shopCommodityCartVO);
                                continue;
                            }
                            shopCommodityCartVO.setCommodityInfoDTO(commodityInfoDTO); //将商品信息加入
                            shopCommodityCartVO.setId(cartDTO.getId());
                            shopCommodityCartVO.setNumber(cartDTO.getNumber());
                            shopCommodityCartVO.setPrice(cartDTO.getPrice());
                            shopCommodityCartVO.setType(cartDTO.getType());
                            shopCommodityCartVO.setSpecificationModel(cartDTO.getSpecificationModel());
                            shopCommodityCartVOS.add(shopCommodityCartVO);
                        }
                    }
                }
            }

            if (shopCommodityCartVOS.size() > 0) {
                shopCommodityVO.setShopCommodityCartVOList(shopCommodityCartVOS);
                shopCommodityVOS.add(shopCommodityVO);
            }

        }

        //获取购物车询盘商品信息
        ArrayList<ShopCommodityVO> shopPurchaseCommodityVOS = new ArrayList<ShopCommodityVO>();
        for (ShopShoppingVO shopShoppingVO : shopShoppingVOList) {
            ShopCommodityVO shopPurchaseCommodityVO = new ShopCommodityVO();
            shopPurchaseCommodityVO.setShopId(shopShoppingVO.getCommodityShopId());//加入该分组的商品所属店铺ID
            ShopInfoDTO shopInfoDTO = iShopInfoService.selectById(shopShoppingVO.getCommodityShopId());
            shopPurchaseCommodityVO.setName(shopInfoDTO.getShopName());//加入该分组的商品所属店铺名称
            shopPurchaseCommodityVO.setShopPayType(shopInfoDTO.getShopPayType());//设置店铺支付类型
            //获取购物车同种商品不通规格列表
            Wrapper<ShopShoppingCartDTO> wrapper = new EntityWrapper<>();
            wrapper.eq("shop_id", bo.getShopId()).eq("type", 1).eq("commodity_shop_id", shopShoppingVO.getCommodityShopId());
            List<ShopShoppingCartDTO> shopShoppingCartDTOList = this.selectList(wrapper);
            ArrayList<ShopCommodityCartVO> shopPurchaseCommodityCartVOS = new ArrayList<ShopCommodityCartVO>();
            for (ShopShoppingCartDTO cartDTO : shopShoppingCartDTOList) {
                if (null != cartDTO.getType() && cartDTO.getType() == 1) {
                    ShopCommodityCartVO shopCommodityCartVO = new ShopCommodityCartVO();
                    PurchaseCommodityBargainDTO purchaseCommodityBargainDTO = iPurchaseCommodityBargainService.selectById(cartDTO.getPurchaseCommodityBargainId());
                    CommodityInfoDTO commodityInfoDTO = new CommodityInfoDTO();
                    BeanUtils.copyProperties(purchaseCommodityBargainDTO, commodityInfoDTO);
                    commodityInfoDTO.setName(purchaseCommodityBargainDTO.getCommodityName());
                    commodityInfoDTO.setLogoUrl(purchaseCommodityBargainDTO.getCommodityLogoUrl());

                    CommodityAttrPriceVO commodityAttrPriceVO = new CommodityAttrPriceVO();
                    commodityAttrPriceVO.setPrice(purchaseCommodityBargainDTO.getPrice());
                    commodityAttrPriceVO.setSpecificationModel(purchaseCommodityBargainDTO.getSpecificationModel());
                    commodityAttrPriceVO.setGoodsId(purchaseCommodityBargainDTO.getPurchaseCommodityId());
                    commodityAttrPriceVO.setType(1);
                    shopCommodityCartVO.setCommodityAttrPriceVO(commodityAttrPriceVO);//将规格价格信息加入

                    shopCommodityCartVO.setCommodityInfoDTO(commodityInfoDTO); //将商品信息加入
                    shopCommodityCartVO.setId(cartDTO.getId());
                    shopCommodityCartVO.setNumber(cartDTO.getNumber());
                    shopCommodityCartVO.setPrice(cartDTO.getPrice());
                    shopCommodityCartVO.setType(cartDTO.getType());
                    shopCommodityCartVO.setSpecificationModel(cartDTO.getSpecificationModel());
                    shopCommodityCartVO.setPurchaseCommodityBargainId(purchaseCommodityBargainDTO.getId());
                    shopPurchaseCommodityCartVOS.add(shopCommodityCartVO);
                }
            }
            if (shopPurchaseCommodityCartVOS.size() > 0) {
                shopPurchaseCommodityVO.setShopCommodityCartVOList(shopPurchaseCommodityCartVOS);
                shopPurchaseCommodityVOS.add(shopPurchaseCommodityVO);
            }
        }
        shopShoppingCartVO.setShopPurchaseCommodityCartVOList(shopPurchaseCommodityVOS);
        shopShoppingCartVO.setShopCommodityVOList(shopCommodityVOS);
        shopShoppingCartVO.setShopCommodityCartVOLoseList(shopCommodityCartVOLoseArrayList);

        return shopShoppingCartVO;
    }

    @Override
    public List<ShopCommodityCartVO> queryHomePageList(ShopShoppingCartBO bo) {
        Wrapper<ShopShoppingCartDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("shop_id", bo.getShopId());
        wrapper.orderBy("create_time", false);//降序
        wrapper.last("limit 10");//只显示3条
        List<ShopShoppingCartDTO> commodityInfoDTOList = this.selectList(wrapper);

        ArrayList<ShopCommodityCartVO> shopCommodityCartVOList = new ArrayList<ShopCommodityCartVO>();
        for (ShopShoppingCartDTO shopShoppingCartDTO : commodityInfoDTOList) {
            ShopCommodityCartVO shopCommodityCartVO = new ShopCommodityCartVO();
            //判断购物车商品是否为询盘
            if (null == shopShoppingCartDTO.getType() || shopShoppingCartDTO.getType() != 1) {
                CommodityInfoDTO commodityInfoDTO = iCommodityInfoService.selectById(shopShoppingCartDTO.getCommodityId());
                shopCommodityCartVO.setCommodityInfoDTO(commodityInfoDTO); //将商品信息加入
                //根据商品ID和规格属性IDS  查出相关属性价格 所需参数店铺ID 。规格属性IDS。规格属性IDs 需要通过购物车查
                Long commodityId = commodityInfoDTO.getId();
                String specification_ids = shopShoppingCartDTO.getSpecificationIds();
                CommodityAttrPriceVO commodityAttrPriceVO = iCommodityInfoService.getShoppingCartGoods(commodityId, specification_ids);
                if (commodityAttrPriceVO.getId() == null) {
                    continue;
                }
                shopCommodityCartVO.setCommodityAttrPriceVO(commodityAttrPriceVO);//将规格价格信息加入
                shopCommodityCartVO.setId(shopShoppingCartDTO.getId());//关联ID
                shopCommodityCartVO.setNumber(shopShoppingCartDTO.getNumber());//购物车数量
                shopCommodityCartVO.setPrice(shopShoppingCartDTO.getPrice());//价格

                //判断商品是否下架
                if (commodityInfoDTO.getIsPublish() == 0) {
                    shopCommodityCartVO.setFailType(0);//失效原因 0下架。1库存没有
                    shopCommodityCartVOList.add(shopCommodityCartVO);
                    continue;
                }

                //或库存为0
                if (commodityAttrPriceVO.getInventoryNumber() <= 0) {
                    shopCommodityCartVO.setFailType(1);//失效原因 0下架。1库存没有
                    shopCommodityCartVOList.add(shopCommodityCartVO);
                    continue;
                }

                //价格对比debug
                if (commodityAttrPriceVO.getPrice().compareTo(shopShoppingCartDTO.getPrice()) < 0) {
                    //此时价格小于加入购入车价格
                    shopCommodityCartVO.setLower(1);//价格是否降低 0正常，1降低
                } else {
                    shopCommodityCartVO.setLower(0);//价格是否降低 0正常，1降低
                }
            }else {
                //查询询盘商品信息
                PurchaseCommodityBargainDTO bargainDTO = iPurchaseCommodityBargainService.selectById(shopShoppingCartDTO.getPurchaseCommodityBargainId());
                CommodityInfoDTO commodityInfoDTO = new CommodityInfoDTO();
                commodityInfoDTO.setName(bargainDTO.getCommodityName());
                commodityInfoDTO.setLogoUrl(bargainDTO.getCommodityLogoUrl());

                CommodityAttrPriceVO commodityAttrPriceVO = new CommodityAttrPriceVO();
                commodityAttrPriceVO.setPrice(shopShoppingCartDTO.getPrice());

                shopCommodityCartVO.setCommodityAttrPriceVO(commodityAttrPriceVO);
                shopCommodityCartVO.setCommodityInfoDTO(commodityInfoDTO); //将商品信息加入
                shopCommodityCartVO.setNumber(shopShoppingCartDTO.getNumber());//购物车数量
                shopCommodityCartVO.setPrice(shopShoppingCartDTO.getPrice());//价格
                shopCommodityCartVO.setId(shopShoppingCartDTO.getId());

            }
            shopCommodityCartVOList.add(shopCommodityCartVO);
        }

        return shopCommodityCartVOList;

    }

    @Override
    public void deleteByCid(Long shopId, Long commodityId, String attrIds) {
        log.info("店铺id : {},商品id : {},规格属性ids : {}", shopId, commodityId, attrIds);
        Wrapper<ShopShoppingCartDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("shop_id", shopId);
        wrapper.eq("commodity_id", commodityId);
        wrapper.eq("specification_ids", attrIds);
        this.delete(wrapper);
        boolean b = this.delete(wrapper);
        if (b) {
            log.info("下单后购物车删除成功!");
        } else {
            log.info("下单后购物车删除失败!");
        }
    }

    @Override
    public boolean addToCartByOrderId(Long orderId) {
        OrderInfoDTO orderInfoDTO =  iOrderInfoService.selectById(orderId);
        Wrapper<OrderCommodityRelationDTO> wrapper = new EntityWrapper<OrderCommodityRelationDTO>();
        wrapper.eq("order_id", orderId);
        List<OrderCommodityRelationDTO> orderCommodityRelationDTOList =  iOrderCommodityRelationService.selectList(wrapper);
        ShopShoppingCartDTO shopdto = new ShopShoppingCartDTO();
        for(OrderCommodityRelationDTO orderCommodityRelationDTO : orderCommodityRelationDTOList){
            shopdto.setCommodityId(orderCommodityRelationDTO.getCommodityId());
            shopdto.setCommodityShopId(orderInfoDTO.getSellShopId());
            shopdto.setShopId(orderInfoDTO.getBuyShopId());
            shopdto.setNumber(orderCommodityRelationDTO.getNum());
            shopdto.setPrice(orderCommodityRelationDTO.getPrice());
            if(orderCommodityRelationDTO.getPurchaseCommodityType() == BargainStateEnum.PURCHASE_COMMODITY_OK.getCode()){//询盘商品
                shopdto.setPurchaseCommodityBargainId(orderCommodityRelationDTO.getPurchaseCommodityBargainId());
                shopdto.setSpecificationModel(orderCommodityRelationDTO.getAttrName());
                shopdto.setType(BargainStateEnum.PURCHASE_COMMODITY_OK.getCode());
            }
            shopdto.setCreateUserId(orderCommodityRelationDTO.getCreateUserId());
            shopdto.setUpdateUserId(orderCommodityRelationDTO.getUpdateUserId());
            shopdto.setSpecificationIds(orderCommodityRelationDTO.getAtrrId());



            //判断是否购物车已有
            Wrapper<ShopShoppingCartDTO> cartWrapper = new EntityWrapper<>();
            if(null !=  shopdto.getShopId()){
                cartWrapper.eq("shop_id", shopdto.getShopId());
            }
            if(null != shopdto.getCommodityId()){
                cartWrapper.eq("commodity_id", shopdto.getCommodityId());
            }
            if(StringUtils.isNotEmpty(shopdto.getSpecificationIds())){
                cartWrapper.eq("specification_ids", shopdto.getSpecificationIds());
            }
            if(StringUtils.isNotEmpty(shopdto.getSpecificationModel())){
                cartWrapper.eq("specification_model",shopdto.getSpecificationModel());
            }
            if(null != shopdto.getType()){
                cartWrapper.eq("type",shopdto.getType());
            }
            if(null != shopdto.getPurchaseCommodityBargainId()){
                cartWrapper.eq("purchase_commodity_bargain_id",shopdto.getPurchaseCommodityBargainId());
            }
            if(null != shopdto.getCommodityShopId()){
                cartWrapper.eq("commodity_shop_id",shopdto.getCommodityShopId());
            }
            if(null != shopdto.getPrice()){
                cartWrapper.eq("price",shopdto.getPrice());
            }

            ShopShoppingCartDTO shopShoppingCartDTO = shopShoppingCartService.selectOne(cartWrapper);

            if(null != shopShoppingCartDTO){
                //购物车已经存在
                shopdto.setId(shopShoppingCartDTO.getId());
                shopdto.setNumber(shopShoppingCartDTO.getNumber() + shopdto.getNumber());
                shopShoppingCartService.updateById(shopdto);
            }else {
                Long pkid = ymlConfig.getPkId();
                shopdto.setId(pkid);
                shopShoppingCartService.insert(shopdto);
            }
        }
        return true;
    }

    @Override
    public boolean addBatch(String saveBOs) {
        List<ShopShoppingCartSaveBO> shopShoppingCartSaveBOS = JSON.parseArray(saveBOs, ShopShoppingCartSaveBO.class);
        for (ShopShoppingCartSaveBO saveBO : shopShoppingCartSaveBOS) {
            if (saveBO != null && saveBO.getCommodityId() != null) {
                add(saveBO);
            }
        }
        return true;
    }

    @Override
    public Result addByCms(String purchaseCommodityBargainIds) {
        if(StrUtils.isEmpty(purchaseCommodityBargainIds)){
            return new Result(CodeEnum.FAIL_100002);
        }

        Long userId = null;
        String userName = "";
        Object object = redisUtil.getSession(CommonParameter.getHeadParamsBO ().getSessionId (), CommonParameter.getHeadParamsBO ().getSource ().toString ());
        if(object == null){
            log.info("没有登录1");
            return new Result(CodeEnum.FAIL_100002);
        }
        if(object instanceof SysUserDTO){
            userId = ((SysUserDTO) object).getId ();
            userName = ((SysUserDTO) object).getName ();
        } else {
            log.info("没有登录2");
            return new Result(CodeEnum.FAIL_100002);
        }
        String[] ids = purchaseCommodityBargainIds.split(",");
        if(ids == null && ids.length == 0){
            log.info("参数为空");
            return new Result(CodeEnum.FAIL_100002);
        }

        saveBatchShopCart(ids, userId, userName);

        return new Result();
    }

    /**
     * 批量价购物车
     * @param ids
     * @param userId
     * @param userName
     */
    @Transactional(rollbackFor= ServiceException.class)
    public void saveBatchShopCart(String[] ids,  Long userId, String userName){
        for(String purchaseCommodityBargainId : ids){
            PurchaseCommodityBargainDTO bargainDTO = iPurchaseCommodityBargainService.selectById(purchaseCommodityBargainId);
            if(bargainDTO == null){
                throw new ServiceException(CodeEnum.FAIL_100002);
            }

            PurchaseInfoDTO purchaseInfoDTO = purchaseInfoService.selectById(bargainDTO.getPurchaseId());
            if(purchaseInfoDTO == null){
                throw new ServiceException(CodeEnum.FAIL_100002);
            }


            if(!(purchaseInfoDTO.getBargainStatus() == 0 || purchaseInfoDTO.getBargainStatus() == 1)){
                throw new ServiceException(CodeEnum.FAIL_100062);
            }

            if(!(bargainDTO.getBargainStatus() == 0 || bargainDTO.getBargainStatus() == 1)){
                throw new ServiceException(CodeEnum.FAIL_100062);
            }

            if(bargainDTO.getBargainStatus() == 0){
                //修改报价商品表
                PurchaseCommodityBargainDTO newBargainDTO = new PurchaseCommodityBargainDTO();
                newBargainDTO.setId(bargainDTO.getId());
                newBargainDTO.setBargainStatus(1);
                newBargainDTO.setShoppingCartStatus(1);
                newBargainDTO.setUpdateUserId(userId);
                newBargainDTO.setUpdateUserName(userName);
                newBargainDTO.setRevision(bargainDTO.getRevision());
                //计算但商品服务费
                newBargainDTO.setPurchaseFeeMoneyScalePrice(setPurchaseFeeMoneyScalePrice(bargainDTO));
                //修改报价商品表
                updateCommodityBargainDTO(newBargainDTO, CodeEnum.FAIL_100065);
                //添加日志 // 0第一次报价、1第一次议价、2第二次报价、3第二次议价、4第三次报价、5拒绝议价、6申请平台议价、7取消报价、8完成报价、9流标
                insertCommodityBargainLog(bargainDTO.getPurchaseId(), bargainDTO.getId(), userId, 8, userId, userName, BigDecimal.ZERO, BigDecimal.ZERO, CodeEnum.FAIL_100065);
            } else {
                //修改报价商品表
                PurchaseCommodityBargainDTO newBargainDTO = new PurchaseCommodityBargainDTO();
                newBargainDTO.setId(bargainDTO.getId());
                newBargainDTO.setShoppingCartStatus(1);
                newBargainDTO.setUpdateUserId(userId);
                newBargainDTO.setUpdateUserName(userName);
                newBargainDTO.setRevision(bargainDTO.getRevision());
                //修改报价商品表
                updateCommodityBargainDTO(newBargainDTO, CodeEnum.FAIL_100065);
            }

            PurchaseInfoDTO newPurchaseInfoDTO = new PurchaseInfoDTO();
            newPurchaseInfoDTO.setId(purchaseInfoDTO.getId());
            newPurchaseInfoDTO.setCancelButtonStatus(1);
            if(!purchaseInfoService.updateById(newPurchaseInfoDTO)){
                throw new ServiceException(CodeEnum.FAIL_100065);
            }
            //TODO: 调用添加购物车接口
            addToCart(bargainDTO.getId(),userId);

        }

    }

    public boolean addToCart(Long id,Long shopId) {
        //查询对应询盘报价数据
        PurchaseCommodityBargainDTO dto = iPurchaseCommodityBargainService.selectById(id);
        if(null == dto){
            return false;
        }

        //获取询盘商品表数据
        PurchaseCommodityVO purchaseCommodityVO = purchaseCommodityService.getPurchaseCommodity(dto.getPurchaseId());
        PurchaseCommodityDTO purchaseCommodityDTO = new PurchaseCommodityDTO();
        BeanUtils.copyProperties(purchaseCommodityVO, purchaseCommodityDTO);

        CommodityInfoDTO commodityInfoDTO = null;
        //判断上品是上架商品还是虚拟商品
//        if(dto.getCommodityPublishType() == 0){
//           //获取商品所属店铺id
//            commodityInfoDTO = iCommodityInfoService.selectById(dto.getCommodityId());
//        }
        //判断是否购物车已有
        Wrapper<ShopShoppingCartDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("status", 1).eq("purchase_commodity_bargain_id", dto.getId())
                .eq("price",dto.getPrice());
        ShopShoppingCartDTO shopShoppingCartDTO = shopShoppingCartService.selectOne(wrapper);
        ShopShoppingCartDTO shopdto = new ShopShoppingCartDTO();
        if (shopShoppingCartDTO != null) {

            return true;
        } else {
            BeanUtils.copyProperties(dto, shopdto);
            Long pkid = ymlConfig.getPkId();
            shopdto.setId(pkid);
            shopdto.setType(1);
            shopdto.setStatus(1);
            shopdto.setCommodityShopId(dto.getShopId());//商品所属的店铺id
            shopdto.setNumber(dto.getNum());
            shopdto.setCommodityId(purchaseCommodityVO.getId());//将询盘商品表id做为商品id
            shopdto.setShopId(shopId);
            shopdto.setPurchaseCommodityBargainId(dto.getId());
            shopdto.setSpecificationModel(purchaseCommodityDTO.getSpecificationModel());
            return shopShoppingCartService.insert(shopdto);
        }
    }
    private void updateCommodityBargainDTO(PurchaseCommodityBargainDTO bargainDTO, CodeEnum codeEnum){
        int revision = bargainDTO.getRevision();
        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("id", bargainDTO.getId());
        wrapper.eq("revision", revision);
        bargainDTO.setRevision(revision + 1);

        boolean a= iPurchaseCommodityBargainService.update(bargainDTO, wrapper);
        if(!a){
            throw new ServiceException(codeEnum);
        }
    }
    /**
     * 计算单商品服务费
     * @param bargainDTO
     * @return
     */
    private BigDecimal setPurchaseFeeMoneyScalePrice(PurchaseCommodityBargainDTO bargainDTO){
        BigDecimal feePrice = BigDecimal.ZERO;
        if(bargainDTO.getPlatBargainStatus() == 5){
            //差价
            BigDecimal flagMoney = BigDecimal.ZERO;
            if(bargainDTO.getThreePrice().compareTo(BigDecimal.ZERO) >0){
                flagMoney = bargainDTO.getTwoPrice().subtract(bargainDTO.getThreePrice());
            } else {
                flagMoney = bargainDTO.getOnePrice().subtract(bargainDTO.getTwoPrice());
            }

            if(flagMoney.compareTo(BigDecimal.ZERO) > 0){
                feePrice = flagMoney.multiply(bargainDTO.getPurchaseFeeMoneyScale());
            }
        }
        return feePrice.setScale(2, BigDecimal.ROUND_UP);
    }
    /**
     * 添加日志
     * @param bargainId
     * @param shopId
     * @param logType 0第一次报价、1第一次议价、2第二次报价、3第二次议价、4第三次报价、5拒绝议价、6申请平台议价、7取消报价、8完成报价、9流标,10平台砍价
     * @param userId
     * @param userName
     * @param oldPrice
     * @param price
     * @param codeEnum
     */
    private void insertCommodityBargainLog(Long purchaseId, Long bargainId, Long shopId, int logType, Long userId, String userName, BigDecimal oldPrice, BigDecimal price, CodeEnum codeEnum){
        PurchaseCommodityBargainLogDTO logDTO = new PurchaseCommodityBargainLogDTO();
        logDTO.setId(ymlConfig.getPkId());
        logDTO.setCommodityBargainId(bargainId);
        logDTO.setShopId(shopId);
        logDTO.setType(logType);
        logDTO.setCreateUserName(userName);
        logDTO.setCreateUserId(userId);
        logDTO.setMoney(oldPrice);
        logDTO.setMoneyBalance(price);
        logDTO.setPurchaseId(purchaseId);
        boolean a = purchaseCommodityBargainLogService.insert(logDTO);

        if (!a) {
            throw new ServiceException(codeEnum);
        }
        if (logDTO.getType () != null){
            if(logDTO.getType () == 0 || logDTO.getType () == 2 || logDTO.getType () == 4){
                PurchaseInfoDTO purchaseInfoDTO = purchaseInfoService.selectById (purchaseId);
                Long sellShopId = purchaseInfoDTO.getShopId ();
                asyncOrderService.sendPurchaseNotice (sellShopId,purchaseId);
            }
        }


    }
    @Override
    public Page<ShopShoppingCartCmsVO> queryShoppingCartPageListByAdmin(ShopShoppingCartCmsBo bo) {
        Page<ShopShoppingCartCmsVO> page = new Page<>(bo.getPageNo(),bo.getPageSize());
        List<ShopShoppingCartCmsVO> page1 = shopShoppingCartMapper.selectByPage(page, bo);
        for (ShopShoppingCartCmsVO shopShoppingCartCmsVO : page1) {
            if (shopShoppingCartCmsVO.getCommodityLogoUrl()==null && shopShoppingCartCmsVO.getCommodityImgUrl()!=null){
                shopShoppingCartCmsVO.setCommodityLogoUrl(shopShoppingCartCmsVO.getCommodityImgUrl());
            }
            if (shopShoppingCartCmsVO.getCommodityLogoUrl()!=null && shopShoppingCartCmsVO.getCommodityImgUrl()==null){
                shopShoppingCartCmsVO.setCommodityLogoUrl(shopShoppingCartCmsVO.getCommodityLogoUrl());
            }
            if(shopShoppingCartCmsVO.getCommodityLogoUrl()!=null && shopShoppingCartCmsVO.getCommodityImgUrl()!=null) {
                shopShoppingCartCmsVO.setCommodityLogoUrl(shopShoppingCartCmsVO.getCommodityLogoUrl()+","+shopShoppingCartCmsVO.getCommodityImgUrl());
            }
            StringBuffer areaName = new StringBuffer();
            areaName = sysAreaService.getParentArea(shopShoppingCartCmsVO.getReceiveAreaId(),areaName);
            shopShoppingCartCmsVO.setReceiveAreaName(areaName.toString());
        }
        page.setRecords(page1);
        return page;
    }

    private ShopShoppingCartDTO getShoppingCartByShopCommodity(Long shopId, Long commodityId, Long commodityShopId) {
        Wrapper<ShopShoppingCartDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("shop_id", shopId);
        wrapper.eq("commodity_id", commodityId);
        wrapper.eq("commodity_shop_id", commodityShopId);

        return this.selectOne(wrapper);
    }
}
